import { createVNode, getCurrentInstance, render, nextTick } from "vue";
import Constructor from "./index.vue";

function useInit() {
  let container;
  async function getModalInstance(props = {}) {
    if (container) {
      return;
    }
    await nextTick();
    const appContext = getCurrentInstance()?.appContext;
    container = document.createElement("div");
    const vNode = createVNode(Constructor, props);
    vNode.appContext = appContext;
    render(vNode, container);
    document.body.append(container);
    props.onVanish = () => {
      render(null, container);
      document.body.removeChild(container);
      container = undefined;
    };
    return vNode;
  }

  function close() {
    render(null, container);
    document.body.removeChild(container);
    container = undefined;
  }

  function show(props) {
    getModalInstance(props);
  }

  return {
    show,
    close
  };
}

export const preview = useInit();
